<?php
/**
 * http Controller
 */
namespace Piz;
class Controller
{
    /**
     * @var \Piz\Router
     */
    protected $router;
    /**
     * @var swoole_http_server->request
     */
    protected $request;
    /**
     * @var swoole_http_server->response
     */
    protected $response;
    /**
     * @var swoole_server
     */
    protected $server;
    /**
     * @var swoole_server->task
     */
    protected $task;
    /**
     * 渲染输出JSON
     * @param array $array
     * @param null  $callback
     */
    final public function json($array=array(),$callback=null){
        $this->gzip ();
        $this->response->header('Content-type','application/json');
        $json = json_encode($array);
        $json = is_null($callback) ? $json : "{$callback}({$json})" ;
        $this->response->end($json);
    }

    /**
     * 渲染模板
     * @param null $file 为空时，
     * @param bool $return true 返回值，false 仅include
     * @return string
     */
    final public function display($param = array() ,$return = false){
        if(!is_array ($param)){
            Log::get_instance()->write('WARNING',"参数类型必须为key=>val式的数组");
        }
        extract($param);
        $this->gzip ();
        $path = Config::get_instance()->get('app.path').'/tpl/'.$this->route['m'].'/'.$this->route['c'] .'/'.$this->route['a'].'.php';
        if(!file_exists ($path)){
            $this->response->status(404);
            $this->response->end("模板不存在：".$path);
            Log::get_instance()->write('WARNING',"模板不存在",$path);
            return ;
        }
        if(!empty(ob_get_contents())) ob_end_clean ();
        ob_start();
        include $path;
        $content = ob_get_contents();
        ob_end_clean();
        $this->response->end($content);
    }

    /**
     * 启用Http GZIP压缩
     * $level 压缩等级，范围是1-9
     */
    final public function gzip($level = NULL  ){
        if($level === NULL ){
            $level = Config::get_instance ()->get('app.gzip',0);
        }
        $level>0 && $this->response->gzip( $level);
    }

    public function __set($name,$object){
        $this->$name = $object;
    }

    public function __get($name){
        return $this->$name;
    }

}